package com.homedo.odin.solution.service.bizservice.personal;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.DateUtils;
import com.homedo.core.common.util.IPUtils;
import com.homedo.core.common.util.ParamCheckUtil;
import com.homedo.odin.solution.contract.personal.brandowner.DataListResp;
import com.homedo.odin.solution.contract.personal.userhomepage.AddPopularityReq;
import com.homedo.odin.solution.contract.personal.userhomepage.AddVisitorReq;
import com.homedo.odin.solution.contract.personal.userhomepage.ClickCountResp;
import com.homedo.odin.solution.contract.personal.userhomepage.CountResp;
import com.homedo.odin.solution.contract.personal.userhomepage.IntroductionResp;
import com.homedo.odin.solution.contract.personal.userhomepage.UpdateUserBannerReq;
import com.homedo.odin.solution.contract.personal.userhomepage.UserBannerResp;
import com.homedo.odin.solution.contract.personal.userhomepage.UserInfoResp;
import com.homedo.odin.solution.contract.personal.userhomepage.UserSolListResp;
import com.homedo.odin.solution.contract.personal.userhomepage.VisitorListResp;
import com.homedo.odin.solution.dao.BrandFirmMapper;
import com.homedo.odin.solution.enumcode.SqlEnum;
import com.homedo.odin.solution.enumcode.brand.FirmStatusEnum;
import com.homedo.odin.solution.enumcode.other.PopularityEnum;
import com.homedo.odin.solution.enumcode.user.RoleEnum;
import com.homedo.odin.solution.model.dto.BrandData;
import com.homedo.odin.solution.model.dto.SolutionOverview;
import com.homedo.odin.solution.model.dto.Visitor;
import com.homedo.odin.solution.model.entity.BrandFirm;
import com.homedo.odin.solution.model.entity.DataBank;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.UserBasic;
import com.homedo.odin.solution.model.entity.UserProfile;
import com.homedo.odin.solution.service.BrandFirmServiceImpl;
import com.homedo.odin.solution.service.DataBankServiceImpl;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.UserBasicServiceImpl;
import com.homedo.odin.solution.service.UserPopularityDetailServiceImpl;
import com.homedo.odin.solution.service.UserProfileServiceImpl;
import com.homedo.odin.solution.service.UserProfileTrackServiceImpl;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: zhaoxudong
 * @date: 2018/3/7 19:04
 * @Description: 用户主页业务处理
 */
@Service
public class UserHomepageBizService {

    private static final Logger logger = LoggerFactory.getLogger(UserHomepageBizService.class);
    @Autowired
    UserProfileServiceImpl userProfileService;
    @Autowired
    UserBasicServiceImpl userBasicService;
    @Autowired
    UserPopularityDetailServiceImpl popularityDetailService;
    @Autowired
    UserProfileTrackServiceImpl trackService;
    @Autowired
    SolutionServiceImpl solutionService;
    @Autowired
    DataBankServiceImpl dataBankService;
    @Autowired
    BrandFirmServiceImpl brandFirmService;
    @Autowired
    CommonBizService commonBizService;

    @Autowired
    BrandFirmMapper brandFirmMapper;

    /**
     * 根据userId查找用户信息
     */
    public UserInfoResp findUserInfoByUserId(Integer userId) {
        ParamCheckUtil.checkUserId(userId);
        UserProfile userProfile = userProfileService.selectByUserId(userId);
        if (userProfile == null) {
            //如果没有用户主页，默认为普通用户
            UserInfoResp infoResp = new UserInfoResp();
            infoResp.setUserId(userId);
            infoResp.setRole(0);
            return infoResp;
        }
        UserInfoResp resp = BeanUtils.transfrom(UserInfoResp.class, userProfile);
        resp.setBanner(userProfile.getBanner());
        resp.setUserId(userId);
        //用户角色如果是品牌主，需要去brandFirm表取审核通过的企业信息
        if (RoleEnum.BRANDOWNER.getDbValue().equals(userProfile.getRole())) {
            BrandFirm firm = brandFirmService.findFirmByUserIdAndStatus(userId, FirmStatusEnum.AUDITPASS.getDbValue());
            if (firm == null) {
                throw new BizException(SqlEnum.FAIL.getCode(), "没有通过审核的品牌商信息");
            }
            resp.setAddress(userProfile.getAddress());
            resp.setIcon(userProfile.getIcon());
            resp.setUserName(userProfile.getUserName());
            resp.setBanner(userProfile.getBanner());

            //如果用户是品牌主则获取品牌主logo
            BrandFirm brandFirm = new BrandFirm();
            brandFirm.setUserId(userId);
            BrandFirm brandFirmSrc = brandFirmMapper.selectOne(brandFirm);
            if (brandFirmSrc != null) {
                resp.setFirmIcon(brandFirmSrc.getFirmIcon());
                resp.setContract(brandFirmSrc.getContact());
                resp.setContractMobile(brandFirmSrc.getContactMobile());
            }
            return resp;
        }
        //如果角色是普通用户或设计师，获取用户名称、头像、地址
        UserBasic userBasic = userBasicService.selectByUserId(userId);
        if (userBasic != null) {
            //优先取昵称 没有就用名称 区别就是名称是账号 名称有可能是一个手机号码
            resp.setUserName(
                    StringUtils.isBlank(userBasic.getNickName()) ? userBasic.getUserName() : userBasic.getNickName());
            resp.setIcon(userBasic.getUserAvatar());
            resp.setAddress(userBasic.getAddress());
        }
        return resp;
    }

    private UserProfile getUserProfileByUserId(Integer userId) {
        UserProfile userProfile = userProfileService.selectByUserId(userId);
        if (userProfile == null) {
            throw new BizException(SqlEnum.FAIL.getCode(), "没有查到用户主页信息");
        }
        return userProfile;
    }

    /**
     * 根据userid获取主页图
     */
    public UserBannerResp findBannerByUserId(Integer userId) {
        UserProfile userProfile = getUserProfileByUserId(userId);
        UserBannerResp resp = new UserBannerResp();
        resp.setBanner(userProfile.getBanner());
        return resp;
    }

    /**
     * 根据userID更新banner
     */
    public void updateBannerByUserId(Integer userId, UpdateUserBannerReq request) {
        String banner = request.getBanner();
        ParamCheckUtil.checkUserId(userId);
        if (StringUtils.isBlank(request.getBanner())) {
            throw new BizException(Meta.CODE_451.getCode(), "banner不能为空");
        }
        Integer count = userProfileService.updateBannerByUserId(userId, banner);
        if (count <= 0) {
            throw new BizException(SqlEnum.FAIL.getCode(), "banner更新失败");
        }
    }

    /**
     * 更新个人简介
     */
    public void updateIntroductionByUserId(Integer userId, String introduction) {
        Integer count = userProfileService.updateIntroductionByUserId(userId, introduction);
        if (count <= 0) {
            throw new BizException(SqlEnum.FAIL.getCode(), "introduction更新失败");
        }
    }

    /**
     * 查看个人简介
     */
    public IntroductionResp findIntroductionByUserId(Integer userId) {
        UserProfile profile = getUserProfileByUserId(userId);
        IntroductionResp resp = new IntroductionResp();
        resp.setIntroduction(profile.getIntroduction());
        return resp;
    }

    /**
     * 获取人气值
     */
    public ClickCountResp findClickCountByUserId(Integer userId) {
        UserProfile profile = getUserProfileByUserId(userId);
        ClickCountResp resp = new ClickCountResp();
        resp.setClickCount(profile.getClickCount());
        return resp;
    }

    /**
     * 获取访问量
     */
    public CountResp findVisitCountByUserId(Integer userId) {
        CountResp resp = new CountResp();
        //获取人气值
        UserProfile profile = getUserProfileByUserId(userId);
        resp.setClickCount(profile.getClickCount());
        //获取总访问量
        Integer totalCount = popularityDetailService.selectCountByType(userId, PopularityEnum.VisitHomepage.getType());
        resp.setTotalCount(totalCount);
        //如果总访问量为0就直接返回结果
        if (totalCount == 0) {
            resp.setTodayCount(0);
            return resp;
        }
        //获取当天访问量
        String today = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        Integer todayCount = popularityDetailService
                .selectCountByTypeAndDate(userId, PopularityEnum.VisitHomepage.getType(), today);
        resp.setTodayCount(todayCount);
        return resp;
    }

    /**
     * 获取主页浏览记录
     */
    public VisitorListResp findVisitorList(Integer userId, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        PageInfo<Visitor> pageInfo = new PageInfo<Visitor>(trackService.selectVisitorList(userId));
        VisitorListResp resp = BeanUtils.transfrom(VisitorListResp.class, pageInfo);
        return resp;
    }

    /**
     * 查找方案列表
     */
    public UserSolListResp selectSols(Integer userId, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        //查找上架中的方案
        PageInfo<Solution> pageInfo = new PageInfo<>(solutionService.selectSolsByUserIdAndStatus(userId, 30));
        UserSolListResp resp = BeanUtils.transfrom(UserSolListResp.class, pageInfo);
        resp.setList(BeanUtils.batchTransform(SolutionOverview.class, pageInfo.getList()));
        return resp;
    }

    /**
     * 获取资料列表
     */
    public DataListResp findDataList(Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<DataBank> pageInfo = new PageInfo<DataBank>(dataBankService.findList(userId));
        DataListResp resp = BeanUtils.transfrom(DataListResp.class, pageInfo);
        resp.setList(BeanUtils.batchTransform(BrandData.class, pageInfo.getList()));
        return resp;
    }

    /**
     * 新增主页访客记录
     */
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public void addVisitor(HttpServletRequest request, AddVisitorReq req) {
        Integer targetId = req.getTargetId();
        Integer visitorId = req.getVisitorId();
        if (targetId == null || targetId <= 0) {
            throw new BizException(Meta.CODE_451.getCode(), "targetId不合规");
        }
        if (targetId.equals(visitorId)) {
            //自己访问自己不增加记录
            return;
        }
        //主页浏览量加1
        userProfileService.updateViewCount(targetId, visitorId, 1);
        //增加访客记录
        trackService.insert(targetId, visitorId, IPUtils.getIpAddr(request));
        //增加人气值
        AddPopularityReq req1 = new AddPopularityReq();
        req1.setOperationId(visitorId);
        req1.setTargetId(targetId);
        req1.setType(PopularityEnum.VisitHomepage.getType());
        commonBizService.addPopularity(req1);
    }

}
